//
//  LoginView.swift
//  IDF
//
//  Created by 陈徐挺 on 22/03/2018.
//  Copyright © 2018 Jesse.chen. All rights reserved.
//

import UIKit
import Reusable
import SVProgressHUD
import YYCache

final class LoginView: UIView, NibOwnerLoadable {

    /*
    // Only override draw() if you perform custom drawing.
    // An empty implementation adversely affects performance during animation.
    override func draw(_ rect: CGRect) {
        // Drawing code
    }
    */
    @IBOutlet weak var phoneTF: UITextField!
    @IBOutlet weak var pwdTF: UITextField!
    @IBOutlet weak var signInBtn: UIButton!
    
    

    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }

    override init(frame: CGRect) {
        super.init(frame: frame)
        self.loadNibContent()
        phoneTF.addTarget(self, action: #selector(textTextFieldContextChange(_:)), for: .editingChanged)
        signInBtn.alpha = 0.4
        signInBtn.isEnabled = false

    }

    @IBAction func siginInClick(_ sender: UIButton) {
        appUser.phone = phoneTF.text!
        appUser.password = pwdTF.text!
        SVProgressHUD.show()
        appUser.login().then { [weak self] _ -> Void in
            initAliyun()
            let cache = YYCache(name: "appcache")
            cache?.setObject(appUser, forKey: "appUser")
            appLogined = true
            if registrationId != "" {
                syncUserRegistration(registrationId)
            }
            self?.removeFromSuperview()
            
        }
    }
    
    @IBAction func registerClick(_ sender: UIButton) {
        pushPhoneViewController(.register)
    }
    @IBAction func forgetpasswordClick(_ sender: UIButton) {
        pushPhoneViewController(.findpassword)
    }

    func pushPhoneViewController(_ type: LoginType) {
        self.removeFromSuperview()
        let next: PhoneViewController = initViewContollerWithStoryboard(storyboardName: "Home", storyboardId: "phoneViewController")
        next.type = type
        nowNavgationController.pushViewController(next, animated: true)
    }

    @objc func textTextFieldContextChange(_ sender: UITextField) {
        let text = sender.text!
        if text.characters.count == 11 && Validate.phoneNum(text).isRight {
            signInBtn.isEnabled = true
            signInBtn.alpha = 1
        } else {
            signInBtn.isEnabled = false
            signInBtn.alpha = 0.4
        }
    }
}
